package xin.lhuo.we.server.controller.user;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import xin.lhuo.we.server.vo.ResultVo;
import xin.lhuo.we.server.enums.ResultEnum;
import xin.lhuo.we.server.service.IPhotoService;
import xin.lhuo.we.server.utils.ResultVoUtil;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author Lhuo
 * @date 2019/5/9 16:02
 */
@Slf4j
@RestController
@RequestMapping(value = "/photo")
public class PhotoController {
    private final IPhotoService photoServer;


    @Autowired
    public PhotoController(IPhotoService photoServer) {
        this.photoServer = photoServer;
    }

    @GetMapping("/uptoken")
    public ResultVo getUpToken() {
        String token = photoServer.getQiNiuUpToken();
        HashMap<String, String> result = new HashMap<>(1);
        result.put("token", token);
        return ResultVoUtil.success(result);
    }

    /**
     * 上传照片到七牛服务器成成功之后回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/callback")
    public HashMap uploadCallback(HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, String> resultMap = new HashMap<>(1);
        try {
            String authorization = request.getHeader("Authorization");
            ServletInputStream inputStream = request.getInputStream();
            photoServer.savePhoto(authorization, inputStream);
            resultMap.put("res", "success");
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
            resultMap.put("res", "fail");
            return resultMap;
        }
    }

    /**
     * 获取指定相册的照片
     *
     * @param albumId
     * @return
     */
    @GetMapping()
    public ResultVo getPhoto(Integer albumId) {
        if (albumId == null) {
            return ResultVoUtil.error(ResultEnum.PARAM_ERROR.getCode(), "相册id不能为空");
        }
        return ResultVoUtil.success(photoServer.getPhoto(albumId));
    }

    /**
     * 删除照片
     *
     * @param id
     * @param key
     * @return
     */
    @DeleteMapping()
    public ResultVo deletePhoto(Integer id, String key) {
        if (id == null) {
            return ResultVoUtil.error(ResultEnum.PARAM_ERROR.getCode(), "照片id不能为空");
        }
        if (StringUtils.isEmpty(key)) {
            ResultVoUtil.error(ResultEnum.PARAM_ERROR.getCode(), "照片key不能为空");
        }
        photoServer.deletePhoto(id, key);
        return ResultVoUtil.success();
    }
}
